package lc20240531;

import lc20240521.TreeNode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

/**
 * @author 不知名帅哥
 * @version 1.0
 * @description TODO
 * @date 2024/5/31 17:26
 */
public class RightTreeView {
    public static void main(String[] args) {
        TreeNode root=new TreeNode(1,new TreeNode(2,null,new TreeNode(5)),new TreeNode(3,null,new TreeNode(4)));
        TreeNode head=new TreeNode(1);
        head.left=new TreeNode(2);
        head.right=new TreeNode(3);
        head.left.left=new TreeNode(4);
        List<Integer> list = rightSideView(head);
        System.out.println(list);
    }

    /**
     * 主要是采用BFS方法遍历，将每一层的末尾值加入List。利用一个for循环，根据size。
     * @param root
     * @return list
     */
    public static List<Integer> rightSideView(TreeNode root) {
        List<Integer> list=new ArrayList<>();
        if (root==null){
            return list;
        }
        Deque<TreeNode> queue=new ArrayDeque<>();
        queue.add(root);
        while (!queue.isEmpty()){
            int size=queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode cur=queue.poll();
                if (cur.left!=null){
                    queue.add(cur.left);
                }
                if (cur.right!=null){
                    queue.add(cur.right);
                }
                if (i==size-1){
                    list.add(cur.val);
                }
            }
        }
        return list;
    }
}
